from utils.time_util import current_time, stamp_time, YYYYMMDDHHMMSS
import json
from PIL import Image
from io import BytesIO
import random
import sqlutils.dbhelper as db
from https.HttpRequest import get_web, post_web
from websites.crmebs.tpy.standard_1 import standard_1

S1 = 3


class api():
    webDB = "crmeb"  # 网站数据库
    baseApi = "http://localhost"
    captchaCodeApi = baseApi + "/adminapi/captcha_pro"  # crmeb登录时的验证码接口
    loginApi = baseApi + "/adminapi/login"  # crmeb后台登录接口
    addGoodsApi = baseApi + "/adminapi/product/product/"  # 新增商品接口
    tokenValue = ""  # 登录token

    def getCaptchaCode(self):
        """
        获取登录验证码
        """
        imgCaptcha = get_web(self.captchaCodeApi)
        if imgCaptcha is not None:
            image = Image.open(BytesIO(imgCaptcha.content))
            if image.mode == 'P' or image.mode == 'RGBA':
                image = image.convert('RGB')
            image.save('../file/CaptchaCode.jpg')
            return True
        else:
            return False

    def crmebLogin(self):
        """
        crmeb登录
        """
        if self.getCaptchaCode():
            captch = input("请输入图片验证码：")
            login = post_web(self.loginApi, {'account': 'admin', 'pwd': 'dxw19950620', 'imgcode': str(captch)})
            if login is not None:
                if login['status'] == 200:
                    global tokenValue
                    tokenValue = "Bearer " + login['data']['token']
                    return "成功"
                else:
                    return "登录失败"
            else:
                return "登录失败"
        else:
            return "获取图片验证码失败"

    def addGoodsInfo(self, p, active, standard, goodsType, baseImgPath, debug=False):
        """
        新增商品信息
        """
        sql = self.standardStr(p, active, standard, goodsType, baseImgPath)
        if debug is False:
            result = post_web(self.addGoodsApi + "0", json.dumps(sql), h={'Authori-zation': tokenValue})
            if result['status'] == 200:
                return True
            else:
                return False
        else:
            print(sql)
            return True

    def standardStr(self, p, active, standard, goodsType, baseImgPath):
        """
        获取不同标准的sql
        """
        sql = {}
        if standard == S1:
            sql = standard_1(p, active, goodsType, baseImgPath)
        return sql

    def addUserToTable(self):
        """
        添加用户信息
        """
        pathImg = "https://xcsm.fun/uploads/attach/2022/06/20220603/82de79947dc3ef290c6fec477afa3bcb.jpg"

        with open("../file/email.txt", "rb") as f:
            accountArray = f.read().decode('utf8').split()
        with open("../file/username.txt", "rb") as f:  # 打开文件
            nameArray = f.read().decode('utf8').split("\n")

        if db.dbconnect(self.webDB) is not None:
            index = 1
            a = min(len(accountArray), len(nameArray))
            for index in range(a):
                sql = r"INSERT INTO eb_user(account,pwd,real_name,nickname,avatar,add_time) VALUES ('" + accountArray[
                    index] + "','123456','admin','" + nameArray[index] + "','" + pathImg + "','" + str(
                    current_time()) + "')"
                db.executeSql(sql)
                print("已插入第" + str(index) + "个用户数据")
                index = index + 1
            return True
        else:
            return False

    def addAppraiseToTable(self, goodsTypeId=None, goodsChildTypeId=None):
        """
        goodsTypeId:            指定商品种类
        goodsChildTypeId:       指定商品种类子类
        批量添加商品评论
        """
        if db.dbconnect(self.webDB) is not None:
            idArr = self.selectGoodsId(goodsTypeId, goodsChildTypeId)
            if idArr is not None:
                sql = "select id,sales from eb_store_product where cate_id in " + idArr
            else:
                sql = "select id,sales from eb_store_product"

            with open("../file/pinglun.txt", "rb") as f:
                comment = f.read().decode('utf8').split()
            with open("../file/username.txt", "rb") as f:  # 打开文件
                nameArray = f.read().decode('utf8').split("\n")

            print("数据库连接成功")
            count = 0
            ##商品ID和销量
            storeInfo = db.select(sql)
            maxOid = db.select("SELECT MAX(oid) from eb_store_order_cart_info;")
            if maxOid is not None and len(maxOid) != 0:
                count = int(maxOid[0]['MAX(oid)']) + 1

            if storeInfo is not None and len(storeInfo) != 0:
                for item in range(len(storeInfo)):
                    ##查商品属性
                    attrInfo = db.select(r"select suk from eb_store_product_attr_value where product_id='" + str(
                        storeInfo[item]['id']) + "'")
                    ##平均每个属性的评论条数
                    averageAppraise = int(int(storeInfo[item]['sales']) * 0.2 / len(attrInfo))

                    for appraise in range(averageAppraise):
                        for attrIndex in range(len(attrInfo)):
                            cateInfo = self.getCartInfo(attrInfo[attrIndex]['suk'])
                            sql = r"INSERT INTO eb_store_order_cart_info (product_id,oid,cart_info) VALUES ('" + str(
                                storeInfo[item]['id']) + "','" + str(count) + "','" + str(cateInfo) + "')"
                            db.executeSql(sql)
                            db.executeSql(self.getAppraiseSql(item, storeInfo, count, comment, nameArray))
                            print("第" + str(count) + "条数据插入完成")
                            count = count + 1
            print("添加评论完成！")
            return True
        else:
            print("数据库连接失败！")
            return False

    def getCartInfo(self, goodsInfo):
        """
        评论购物详情
        """
        return '{"id":"4264052052651409408","type":0,"seckill_id":0,"bargain_id":0,"combination_id":0,"advance_id":0,"product_id":186,"product_attr_unique":"8febf001","cart_num":1,' \
               '"productInfo":{"id":1880,"mer_id":0,"image":"https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01oEU4Ib1ptUdg7aZAp_!!2213295655418-0-cib.jpg","recommend_image":"",' \
               '"slider_image":["https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01oEU4Ib1ptUdg7aZAp_!!2213295655418-0-cib.jpg","https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01O5AuhR1ptUdbUhuGi_!!2213295655418-0-cib.jpg","https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01nQ25sT1ptUdWdd3Xs_!!2213295655418-0-cib.jpg","https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN017aablY1ptUdgswtVl_!!2213295655418-0-cib.jpg","https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01Tg9Zc11ptUdgsxEIj_!!2213295655418-0-cib.jpg"],' \
               '"store_name":"\u897f\u5f0f\u7cd5\u70b9\u542f\u82ac\u5de7\u514b\u529b\u7194\u5ca9\u86cb\u7cd55\u679a\u4e0b\u5348\u8336\u5c0f\u70b9\u5fc3\u529e\u516c\u5ba4\u4f11\u95f2\u96f6\u98df","store_info":"\u897f\u5f0f\u7cd5\u70b9\u542f\u82ac\u5de7\u514b\u529b\u7194\u5ca9\u86cb\u7cd55\u679a\u4e0b\u5348\u8336\u5c0f\u70b9\u5fc3\u529e\u516c\u5ba4\u4f11\u95f2\u96f6\u98df","keyword":"\u5c0f\u70b9\u5fc3,\u4e0b\u5348\u8336,\u897f\u5f0f",' \
               '"bar_code":"","cate_id":"15","price":"9.00","vip_price":"0.00","ot_price":"11.00","postage":"0.00","unit_name":"\u4ef6","sort":0,"sales":215,"stock":4995,"is_show":1,"is_hot":0,"is_benefit":0,"is_best":0,"is_new":0,"is_virtual":0,"virtual_type":0,"add_time":1654238642,"is_postage":0,"is_del":0,"mer_use":0,"give_integral":"0.00","cost":"9.00","is_seckill":0,"is_bargain":0,"is_good":0,"is_sub":0,"is_vip":0,"ficti":0,"browse":0,"code_path":"","soure_link":"",' \
               '"video_link":"","temp_id":1,"spec_type":1,"activity":"0,1,2,3","spu":"5056101522961","label_id":"","command_word":"","recommend_list":"","vip_product":0,"presale":0,"presale_start_time":0,"presale_end_time":0,"presale_day":1,"logistics":"1","freight":4,"custom_form":"[]","attrInfo":{"id":7226,"product_id":1880,' \
               '"suk":"' + goodsInfo + '","stock":999,"sales":0,"price":"9.00","image":"https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01oEU4Ib1ptUdg7aZAp_!!2213295655418-0-cib.jpg","unique":"8febf001","cost":"9.00","bar_code":"","ot_price":"11.00","vip_price":"0.00","weight":"0.00","volume":"0.00","brokerage":"0.00",' \
                                       '"brokerage_two":"0.00","type":0,"quota":0,"quota_show":0,"is_virtual":0,"coupon_id":0,"disk_info":""},"express_delivery":True,"store_mention":False},"attrInfo":{"id":7226,"product_id":1880,' \
                                       '"suk":"\u7194\u5ca9\u86cb\u7cd5-5\u679a\u8bd5\u5403\u88c5","stock":999,"sales":0,"price":"9.00","image":"https:\/\/cbu01.alicdn.com\/img\/ibank\/O1CN01oEU4Ib1ptUdg7aZAp_!!2213295655418-0-cib.jpg","unique":"8febf001","cost":"9.00","bar_code":"","ot_price":"11.00","vip_price":"0.00","weight":"0.00","volume":"0.00","brokerage":"0.00","brokerage_two":"0.00","type":0,"quota":0,"quota_show":0,"is_virtual":0,"coupon_id":0,"disk_info":""},"sum_price":"9.00","truePrice":9,' \
                                       '"trueStock":999,"costPrice":"9.00","attrStatus":True,"vip_truePrice":0,"price_type":"level","is_valid":1,"postage_price":"15.00","use_integral":0,"integral_price":0,"coupon_price":0,"one_brokerage":"0.90","two_brokerage":"0.45","staff_brokerage":"0.00","agent_brokerage":"0.00","division_brokerage":"0.00","sum_true_price":"9.00"}'

    def getAppraiseSql(self, item, storeInfo, count, comment, nameArray):
        """
        获取评论SQL
        """
        startTime = stamp_time("2022-01-20 08:00:00", fmt_str=YYYYMMDDHHMMSS)  # 1609675067
        endTime = stamp_time("2022-07-23 08:00:00", fmt_str=YYYYMMDDHHMMSS)  # 1654257467
        userImg = "https://xcsm.fun/uploads/attach/2022/06/20220603/mid_ed1a714eccead9417b0213f393a97194.png"

        id = str(storeInfo[item]['id'])
        oid = str(count)
        productScore = str(random.randint(3, 5))
        serviceScore = str(random.randint(3, 5))
        commentStr = comment[random.randint(1, len(comment) - 10)]
        nameStr = nameArray[random.randint(1, len(nameArray) - 10)]
        timeStr = str(random.randint(startTime, endTime))
        return r"INSERT INTO eb_store_product_reply (product_id,oid,product_score,service_score,comment,nickname,avatar,add_time) VALUES ('" + id + "','" + oid + "','" + productScore + "','" + serviceScore + "','" + commentStr + "','" + nameStr + "','" + userImg + "','" + timeStr + "')"

    def selectGoodsId(self, goodsTypeId, goodsId):
        """
        查询商品子类Id
        """

        if goodsTypeId is None and goodsId is None:
            return None

        idArr = []
        sqlStr = ""
        if goodsTypeId is not None:
            storeInfo = db.select("select cate_id from eb_store_product_cate where cate_pid=" + str(goodsTypeId))
            if storeInfo is not None and len(storeInfo) != 0:
                for item in storeInfo:
                    if item["cate_id"] not in idArr:
                        idArr.append(item["cate_id"])

        if goodsId is not None:
            idArr.append(goodsId)

        for item in idArr:
            sqlStr = sqlStr + str(item) + ","
        return "(" + sqlStr[0:-1] + ")"
